// JavaScript Document
/*==============================(^_^)==============================*\
@ ################################################################# @
@ # Validate form			                                      # @
@ # Coded by Harry Nguyen                                         # @
@ # Company: Megaleap (http://www.megaleap.com)                   # @
@ # Email: harrynguyenhung@gmail.com                              # @
@ ################################################################# @
\*==============================(^_^)==============================*/


function isValid(theform){
     for(var i=0;i<theform.elements.length;i++){	 
          var el=theform.elements[i];
		  shortFieldName=el.id;
          el.value=el.value.replace(/^ {1,}/,"").replace(/ {1,}$/,"").replace(/ {2,}/," ");
          if(!isCharAllowed(el, "")) return false;
          if(el.name.substring(0,2)=="rq" && el.type != "hidden"){
	/*	  
                if( ((el.type=="text"  || el.type=="textarea" || el.type=="password") && el.value=="") || (el.type=="select-one" && (el.selectedIndex==0 || el.value == "")) )
					return errorFound(el, "Please make sure the "+shortFieldName+" field was properly completed.");         		             
				else
				if( (el.type=="checkbox" || el.type=="radio") && !isChecked(eval("theform."+el.name)) )  
					return errorFound(el, "Please choose at least one "+shortFieldName+" .");         		             				
*/					
					if (isEmpty(el) == false) return false;
          }
    }
	return true;
}

function isEmpty(el)
{
    el.value=el.value.replace(/^ {1,}/,"").replace(/ {1,}$/,"").replace(/ {2,}/," ");
	shortFieldName= (el.id=="" ? el.name:el.id);
	if( ((el.type=="text"  || el.type=="textarea" || el.type=="password") && el.value=="") || (el.type=="select-one" && (el.value == "")) )			//el.selectedIndex==0 || 
		return errorFound(el, "Please make sure the "+shortFieldName+" field was properly completed.");         		             
	else
	if( (el.type=="checkbox" || el.type=="radio") && !isChecked(eval("theform."+el.name)) )  
		return errorFound(el, "Please choose at least one "+shortFieldName+" .");  
	return true;
}

function isValidZipCode(value) {
   var re = /^\d{5}([\-]\d{4})?$/;
   return (re.test(value));
}

function isCharAllowed(obj, f){
     var p;
	 var name = obj.name;
	 f = (f!="") ? f:name.substring(name.lastIndexOf("_"), name.length);
	 if (obj.value=="") return true;
     if(f=="_zip"){					//zipcode
   	      p=/^\d{5}([\-]\d{4})?$/;
          if(!p.test(obj.value))
	          return errorFound(obj, "Please enter zipcode correct with format 92614(-1236).");	 
     }	     
     if(f=="_sta"){					//state short
   	      p=/^[a-z]{1,}$/i;
          if(!p.test(obj.value) || obj.value.length != 2)
	          return errorFound(obj, "Please enter State correct!");	 
     }	  
     if(f=="_pe"){					//phone number	 
		  p=/^\(?\d{3}\)? ?\d{3}[-.]\d{4}$/i;
          if(!p.test(obj.value))
	          return errorFound(obj, "Please enter Phone correct with format correct (999) 222-5555");	 
     }	  	         
	  	  
	 if(f=="_nn"){					// number 
   	      p=/^[0-9]{1,}$/;
          if(!p.test(obj.value))
	          return errorFound(obj, "Please enter only numbers 0 - 9");	 
	 }		 
 	 if(f=="_ni"){					//number > 0
   	      p=/^[0-9]{1,}$/;
          if(!p.test(obj.value) || obj.value ==0 || obj.value.charAt(0) == "0")
	          return errorFound(obj, "Please enter only numbers > 0");	 
	 }		 
	  if(f=="_ss"){					// character
   	      p=/^[a-z\ ]{1,}$/i;
          if(!p.test(obj.value))
	          return errorFound(obj, "Please enter only character");	 
	 }	
     if(f=="_c"){
          p=/^[a-zA-Z''-\. ]{0,}$/;
          if(!p.test(obj.value))
          	  return errorFound(obj,"Please enter only letters and ' , - .")
     }	 
	  if(f=="_ns"){					// number and character
   	      p=/^[a-z0-9]{1,}$/i;			
          if(!p.test(obj.value))
	          return errorFound(obj, "Please enter only character and number");	 
	 }	
	  if(f=="_nss"){					// number and character and space
   	      p=/^[a-z0-9\ ]{1,}$/i;			
          if(!p.test(obj.value))
	          return errorFound(obj, "Please enter only character, number and space");	 
	 }		 
	  if(f=="_nm"){				//money
   	      p=/^[0-9\.]{1,}$/i;
          if( (!p.test(obj.value) || obj.value ==0 || obj.value.charAt(0) == "0") && obj.value.substring(0,2)!="0.")
	          return errorFound(obj, "Please enter only number > 0");	 
	 }	
	 if(f=="_nd"){			//date		-- not working properly -- need test againt
          if(!isDate(obj.value))
	          return errorFound(obj, "Please enter a valid date in MM/DD/YYYY format");	 
	 }
     if(f=="_date"){		// date
          p=/^\d{1,2}\/\d{1,2}\/\d{4}$/;
          if(!p.test(obj.value))
	          return errorFound(obj, "Please enter a valid date in format MM/DD/YYYY");
     }	 
	 if(f=="_em"){			//email
          p=/^((?:(?:(?:(\w|~)[~\.\-\+]?)*)(\w|~))+)\@((?:(?:(?:\w[\.\-\+]?){0,62})\w)+)\.([a-zA-Z]{2,6})$|^$/;		
			var p1 = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;    
//		  \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
          if(!p.test(obj.value) || !isEmail(obj) || !p1.test(obj.value))
         	 return errorFound(obj,"Please enter a valid email");
	 }	 	 
	if(f=="_add"){			// address
          p=/^[a-zA-Z''-\.0-9\/ ]{0,}$/;
         if(!p.test(obj.value))
	         return errorFound(obj, "Please enter a valid address");
    }
	if(f=="_ssc"){			// social security number
    	valid(obj,/\d{3}-\d{2}-\d{4}/i, "Please enter a valid social security number");
    }
	/*
     if(f=="_ccn"){
          p=/^((?:4\d{3})|(?:5[1-5]\d{2})|(?:6011)|(?:3[68]\d{2})|(?:30[012345]\d))[ -]?(\d{4})[ -]?(\d{4})[ -]?(\d{4}|3[4,7]\d{13})$/;
          if(!p.test(obj.value))
         	 return errorFound(obj, "Credit card number invalid);
     }
	 */     	 	
	 /*

     if(f=="rqw"){
          p=/^[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?$/;
//		  http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
          if(!p.test(obj.value))
          return errorFound(obj,"Please enter a valid URL, without \"http://\"");
     }
     if(f=="rqm"){
          p=/^[0-9''""]{1,}$/;
          if(!p.test(obj.value))
          return errorFound(obj, "Please enter only numbers and symbols \",'");
     }     	 
	*/
     return true;
}

function valid(obj, p, mes){
//alert(p.test(obj.value));
	if(p!="" && !p.test(obj.value)) return errorFound(obj, mes);
	return true;
}
function isChecked(obj){
	for(i=0; i<obj.length; i++){
		if(obj[i].checked==true)
			return true;
	}
	return false;
}

// helper function, returns false if any character in string argument is not found in valid argument
function isMatch(string,valid){
   if (!string) return false;
   var check = string.split('');
   for(var i = 0; i < check.length; i++) {
      if(valid.indexOf(check[i]) == -1) return false;
   }
   return true;
}

function isNotMatch(string,valid){
   if (!string) return false;
   var check = string.split('');
   for(var i = 0; i < check.length; i++) {
      if(valid.indexOf(check[i]) == -1) return false;
   }
   return true;
}

function errorFound(obj,msg){
    if(msg)alert(msg);
    obj.focus();	 
	if (obj.type=="text" || obj.type=="textarea" || obj.type=="password"){
	    obj.style.backgroundColor="#ff6666";
		obj.select();
	}
     obj.onclick=mkwhite;
     obj.onkeydown=mkwhite;
     return false;
}
function mkwhite(){this.style.backgroundColor="ffffff";}

function isEmail (tempobj){
	var str=tempobj.value;
	var strSplit = str.split(" ")	
	if (strSplit.length > 1) 
		return errorFound(tempobj, "You EMAIL is invalid, please check for spaces.")
			
	var filter=/.+@.+\.[a-zA-Z]{2,3}$/
	var isValid = filter.test(str);
	if (!isValid) {
		return errorFound(tempobj, "You EMAIL is invalid, please check it again.")
	}
	return true;
}




//Date validations
function makeDate(str) {
   dArr = str.split('/')
   mm = parseInt(dArr[0],10);
   dd = parseInt(dArr[1],10);
   yy = parseInt(dArr[2],10);
   return new Date(yy,(mm-1),dd);
}

function isDate(str) {   
   if (!str) return false;
   if (str.length<10) { 
      strArr = str.split('/');
	  strArr[0] = (strArr[0].length==1)?"0"+strArr[0]:strArr[0];
	  strArr[1] = (strArr[1].length==1)?"0"+strArr[1]:strArr[1];
	  strArr[2] = (strArr[2].length==1)?"0"+strArr[2]:strArr[2];
	  str = strArr.join('/');
   }
   testDate = makeDate(str)
   if (isNaN(testDate)) return false;
   tyy = testDate.getYear();
   tmm = testDate.getMonth()+1
   tdd = testDate.getDate();
   strTyy = tyy.toString();
   tmm = (tmm<10)?"0"+tmm:tmm;
   tdd = (tdd<10)?"0"+tdd:tdd;
   newStr = ''+tmm+'/'+tdd+'/'+tyy
   return (str==newStr);
}
function dateDiff(d1,d2) {
   date1 = makeDate(d1);   
   if (isNaN(date1)) return -1;   
   date2 = makeDate(d2);
   if (isNaN(date2)) return -1;      
   return date2.getTime()-date1.getTime(); // date2 must be greater than date 1
}


function isEqualToDate(obj){
	var d = new Date();
	var str = obj.value;
	var today = (d.getMonth()+1) + "/" + d.getDate() +"/" + d.getYear();
	if (Date.parse(today) > Date.parse(str)) 
		return errorFound(obj, obj.id + " must greater than or equals Today!")	
	return true;
}

function checkdate(start, end){
	var datefrom = start;
	var dateto = end;
 	if (!isDate(datefrom.value) || datefrom.value == "") { 	
        alert("Invalid date entry. Please enter a valid date in MM/DD/YYYY format")
        datefrom.focus();
        return false;
	   }
	if (!isDate(dateto.value) || dateto.value == "") {
        alert("Invalid date entry. Please enter a valid date in MM/DD/YYYY format")
        dateto.focus();
        return false;
	   }
	if (dateDiff(datefrom.value,dateto.value)<0) {
        alert("Invalid date entries. " + dateto.id + " must be greater than " + datefrom.id);
        dateto.select();
        return false;
	   }	   
	 
	 return true;
}	






function makeDate(str) {
   dArr = str.split('/')
   mm = parseInt(dArr[0],10);
   dd = parseInt(dArr[1],10);
   yy = parseInt(dArr[2],10);
   return new Date(yy,(mm-1),dd);
}

function dateDiff(d1,d2) {
   date1 = makeDate(d1);
   if (isNaN(date1)) return -1;   
   date2 = makeDate(d2);
   if (isNaN(date2)) return -1;      
   return date2.getTime()-date1.getTime(); // date2 must be greater than date 1
}